<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\PictureLiveUploadsFileController;
use App\Models\PictureLive;
use App\Models\PictureLiveVote;
use App\Models\UserInfo;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 图片直播作品管理
 */
class PictureLiveWorksController extends CommonController
{
    protected $model;
    protected $validate;

    public function __construct()
    {
        parent::__construct();

        $this->model = new \App\Models\PictureLiveWorks();
        $this->validate = new  \App\Validate\PictureLiveWorksValidate();
    }


    /**
     * 获取图片列表
     * @param act_id int 活动id
     * @param user_id int 用户id
     * @param limit int 分页大小
     * @param keywords string 搜索关键词(文章标题)
     * @param start_time datetime 开始时间(开始)
     * @param end_time datetime 结束时间(开始)
     * @param sort 字段排序  1 默认  2 浏览量  3 点赞 
     * @param order 排序方式  1 正序 2倒序
     */
    public function lists()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $sort = $this->request->sort;
        $order = $this->request->order;
        $user_id = $this->request->user_info['id'];

        // for($i = 1;$i<1500;$i++){
        //     $a = '2023-05-'.mt_rand(10,29).' '.mt_rand(10,23).':10:10';
        //     DB::table('picture_live_works')->insert(['user_id'=>1,'act_id'=>13
        //     ,'title'=>getRndString(5)
        //     ,'cover'=>'img/2023-04-26/hENksnydcl8laXyX39Rz77z3s5AMRJ7e8LgH14yN.jpg'
        //     ,'img'=>'img/2023-04-26/hENksnydcl8laXyX39Rz77z3s5AMRJ7e8LgH14yN.jpg'
        //     ,'thumb_img'=>'img/2023-04-26/hENksnydcl8laXyX39Rz77z3s5AMRJ7e8LgH14yN.jpg'
        //     ,'serial_number'=>'P'.getRndUpperString(7)
        //     ,'status'=>1
        //     ,'width'=>736
        //     ,'height'=>481
        //     ,'size'=>73713
        //     ,'ratio'=>'736x481'
        //     ,'create_time'=>$a
        // ]);
        // }
        // echo '完成';die;

        $res = $this->model->lists(
            ['id', 'act_id', 'user_id', 'title', 'cover', 'thumb_img', 'width', 'height', 'size', 'ratio', 'browse_num', 'vote_num', 'create_time'],
            $this->request->act_id,
            null,
            $keywords,
            1,
            null,
            null,
            2,
            $sort,
            $order,
            $limit
        );

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        foreach ($res['data'] as $key => $val) {
            if ($val['user_id']) {
                $wechat_info = UserInfo::getWechatField($val['user_id'], ['nickname', 'head_img']);
                $res['data'][$key]['nickname'] = $wechat_info['nickname'];
                $res['data'][$key]['head_img'] = $wechat_info['head_img'];
            } else {
                $res['data'][$key]['nickname'] = '';
                $res['data'][$key]['head_img'] = $this->getImgAddrUrl() . 'default/default_head_img.png';
            }
            $res['data'][$key]['size'] = format_bytes($val['size']); //格式化字节数


            $pictureLiveModel = new PictureLive();
            $pictureLiveVoteModel = new PictureLiveVote();
            $act_info = $pictureLiveModel->detail($val['act_id'], 1, ['id', 'vote_way', 'number', 'con_start_time', 'con_end_time', 'vote_start_time', 'vote_end_time']);
            if ($user_id) {
                $res['data'][$key]['user_vote_num'] = $pictureLiveVoteModel->userVoteNum($act_info['vote_way'], $user_id, $val['act_id'], $val['id']); //用户点赞数
            } else {
                $res['data'][$key]['user_vote_num'] = 0; //获取用户当前作品的点赞量
            }
            list($act_info->vote_msg, $act_info->vote_number) = $pictureLiveVoteModel->getVoteNum($act_info->vote_way, $act_info->number, $user_id, $val['act_id']);
            $res['data'][$key]['picture_live'] = $act_info;
        }

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 获取图片详情 
     * @param id int id
     * @param token 用户token
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];
        $field = ['id', 'act_id', 'user_id', 'title', 'cover', 'thumb_img', 'width', 'height', 'size', 'ratio', 'browse_num', 'vote_num', 'create_time'];
        $res = $this->model->detail($this->request->id, 1, $field);

        if (!$res) {
            return $this->returnApi(202, "图片不存在");
        }
        $res = $res->toArray();
        if ($res['user_id']) {
            $wechat_info = UserInfo::getWechatField($res['user_id'], ['nickname', 'head_img']);
            $res['nickname'] = $wechat_info['nickname'];
            $res['head_img'] = $wechat_info['head_img'];
        } else {
            $res['nickname'] = '';
            $res['head_img'] = '';
        }
        $res['size'] = format_bytes($res['size']); //格式化字节数

        $pictureLiveModel = new PictureLive();
        $pictureLiveVoteModel = new PictureLiveVote();
        $act_info = $pictureLiveModel->detail($res['act_id'], 1, ['id', 'vote_way', 'number', 'con_start_time', 'con_end_time', 'vote_start_time', 'vote_end_time']);
        if ($user_id) {
            $res['user_vote_num'] = $pictureLiveVoteModel->userVoteNum($act_info['vote_way'], $user_id, $res['act_id'], $res['id']); //用户点赞数
        } else {
            $res['user_vote_num'] = 0; //获取活动状态
        }
        list($act_info->vote_msg, $act_info->vote_number) = $pictureLiveVoteModel->getVoteNum($act_info->vote_way, $act_info->number, $user_id, $res['act_id']);
        $res['picture_live'] = $act_info;

        //更新浏览量
        $this->model->updateBrowseNumber($this->request->id, 10, 30);
        return $this->returnApi(200, "查询成功", true, $res);
    }


    /**
     * 作品点赞
     * @param token  用户token
     * @param works_id 作品id
     */
    public function  worksVote()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_works_vote')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];

        Log::info(date('Y-m-d H:i:s') . '~用户id：' . $user_id . '；作品id：' . $this->request->works_id . ';ip地址：' . request()->ip());

        // $ip = [
        //     '112.98.169.75',
        //     '222.180.68.57',
        //     '223.104.251.49',
        //     '183.230.215.93',
        // ];
        // if(in_array(request()->ip() , $ip)){
        //     return $this->returnApi(201, "系统检测到你存在刷票行为，暂时取消你的点赞资格");
        // }

        //限制用户多次点击
        $key = md5($user_id . $this->request->works_id . request()->ip());

        $oldKey =  Cache::get($key); //没有缓存返回false
        if ($oldKey > mt_rand(6, 10)) {
            return $this->returnApi(201, "您操作的太频繁了，请稍后重试");
        } else {
            $cache_data = $oldKey ? $oldKey + 1 : 1;
            Cache::put($key, $cache_data, 10); //10秒钟之内只能点击6~10次
        }
        $worksInfo = $this->model->find($this->request->works_id);
        if (empty($worksInfo)) {
            return $this->returnApi(201, "参数错误");
        }
        if ($worksInfo['status'] != 1) {
            Log::info('当前作品未审核通过，不允许点赞-' . date('Y-m-d H:i:s') . '~用户id：' . $user_id . '；作品id：' . $this->request->works_id . ';ip地址：' . request()->ip());

            return $this->returnApi(201, "当前作品未审核通过，不允许点赞");
        }

        $pictureLiveModel = new PictureLive();
        $act_info = $pictureLiveModel->detail($worksInfo->act_id, 1, ['id', 'vote_way', 'number', 'vote_start_time', 'vote_end_time']);

        if (empty($act_info)) {
            return $this->returnApi(201, "参数错误");
        }
        if ($act_info['vote_way'] == 3) {
            return $this->returnApi(201, "此活动无需点赞");
        }

        if ($act_info['vote_start_time'] > date('Y-m-d H:i:s')) {
            return $this->returnApi(201, "点赞未开始，暂不允许点赞");
        }
        if ($act_info['vote_end_time'] < date('Y-m-d H:i:s')) {
            return $this->returnApi(201, "点赞已结束，不允许点赞");
        }

        $pictureLiveVoteModel = new PictureLiveVote();
        if ($act_info['vote_way'] == 1) {
            //查看用户共投了好多票
            $user_vote_num = $pictureLiveVoteModel->getVoteNumber($user_id, $act_info['id']); //用户点赞数量

            if ($act_info['number'] !== 0 && $act_info['number'] <= $user_vote_num) {
                return $this->returnApi(202, "点赞次数已达到上限");
            }
        } else {
            $user_vote_num = $pictureLiveVoteModel->getVoteNumber($user_id, $act_info['id'], null, date('Y-m-d')); //用户点赞数量

            if ($act_info['number'] !== 0 && $act_info['number'] <= $user_vote_num) {
                return $this->returnApi(202, "今日点赞次数已达到上限，请明日再来！");
            }
        }

        DB::beginTransaction();
        try {
            $worksInfo->vote_num = ++$worksInfo->vote_num;
            $worksInfo->save();

            $pictureLiveVoteModel->add([
                'act_id' => $act_info['id'],
                'works_id' => $this->request->works_id,
                'yyy' => date('Y'),
                'mmm' => date('m'),
                'ddd' => date('d'),
                'date' => date('Y-m-d'),
                'user_id' => $user_id,
                'terminal' => 'wx',
            ]);

            DB::commit();
            return $this->returnApi(200, "点赞成功", true, ['user_vote_num' => $user_vote_num + 1]); //返回用户已点赞数量
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, "点赞失败");
        }
    }

    /**
     * 撤销、删除、重新上传作品
     * @param token  用户token
     * @param works_id 作品id
     * @param status 状态 3.未审核 4.已撤销 5已删除 
     */
    public function  worksCancelAndDel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_works_cancel_del')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];

        $result = $this->model->find($this->request->works_id);
        if (empty($result)) {
            return $this->returnApi(201, "参数错误");
        }
        if ($result['user_id'] != $user_id) {
            return $this->returnApi(201, "网络错误");
        }
        if ($this->request->status == 4 &&  $result['status'] != 3) {
            return $this->returnApi(201, "此状态不允许撤销");
        } elseif ($this->request->status == 5 &&  ($result['status'] != 4 && $result['status'] != 2)) {
            return $this->returnApi(201, "此状态不允许删除");
        } elseif ($this->request->status == 3 &&  $result['status'] != 4) {
            return $this->returnApi(201, "此状态不允许重新上传");
        }
        $status_msg = $this->request->status == 3 ? '重新上传' : ($this->request->status == 4 ? '撤销' : '删除');

        DB::beginTransaction();
        try {
            $result->status = $this->request->status;
            $res = $result->save();

            /*消息推送*/
            //  $system_id = $this->systemAdd($status_msg . '投稿的作品', $user_id, null, 18, intval($result->id), '作品：【' . $result->title . '】' . $status_msg . '成功');

            /**执行积分规则 */  //撤销才执行，因为删除的作品，必须是撤销的
            // if (!empty($result->score) && $this->request->status == 1) {
            //     $scoreRuleObj = new ScoreRuleController();
            //     $score_msg = $scoreRuleObj->getScoreMsg($result->score);
            //     $scoreRuleObj->scoreReturn($this->score_type, $result->score, $result->user_id, '撤销作品，' . $score_msg . ' ' . abs($result->score) . ' 积分', $system_id);
            // }

            if ($this->request->status == 5) {
                $this->deleteFile([$result['img'], $result['cover'], $result['thumb_img']]); //删除文件
            }

            DB::commit();
            return $this->returnApi(200, $status_msg . "成功", true, $res);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $status_msg . "失败");
        }
    }


    /**
     * 获取剩余可上传图片张数
     * @param id int 活动id  
     * @param token 用户token
     */
    public function surplusUploadsNumber()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_surplus_uploads_number')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $pictureLiveModel = new PictureLive();
        $user_id = $this->request->user_info['id'];
        $field = [
            'id', 'title', 'main_img', 'img', 'con_start_time', 'con_end_time', 'vote_start_time', 'vote_end_time', 'address',
            'uploads_number', 'uploads_way', 'is_appoint', 'intro', 'browse_num', 'qr_url', 'create_time', 'theme_color', 'animation', 'animation_time'
        ];
        $res = $pictureLiveModel->detail($this->request->id, 1, $field);

        if (!$res) {
            return $this->returnApi(202, "活动不存在或已结束");
        }
        $res = $res->toArray();

        //获取用户剩余上传作品数量
        $surplus_uploads_number = $pictureLiveModel->surplusUploadsNumber($this->request->id, $user_id, $res); //-1 无上传权限(已去掉，改为 0)

        return $this->returnApi(200, "查询成功", true, ['surplus_uploads_number' => $surplus_uploads_number]);
    }
    /**
     * 图片直播，上传图片
     * @param token 用户token
     * @param act_id int 活动id
     * @param picture_live file 上传文件 名
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];
        $pictureLiveModel = new PictureLive();
        $act_info = $pictureLiveModel->detail($this->request->act_id, 1, ['con_start_time', 'con_end_time', 'vote_start_time', 'vote_end_time', 'uploads_number', 'uploads_way', 'is_appoint', 'is_check']);
        if (empty($act_info)) {
            return $this->returnApi(201, "活动不存在");
        }
        $act_info = $act_info->toArray();
        if ($act_info['con_start_time'] > date('Y-m-d H:i:s', strtotime("+1 hour"))) {
            return $this->returnApi(201, "活动未开始，暂不允许上传");
        }
        if ($act_info['con_end_time'] < date('Y-m-d H:i:s', strtotime("-1 hour"))) {
            return $this->returnApi(201, "活动已结束，不允许上传");
        }
        //判断是否可以上传
        $userIsCanUploadsAndNumber = $pictureLiveModel->userIsCanUploadsAndNumber($this->request->act_id, $user_id, $act_info);
        if ($userIsCanUploadsAndNumber !== true) {
            return $this->returnApi(201, $userIsCanUploadsAndNumber);
        }

        $pictureLiveUploadsFileObj = new PictureLiveUploadsFileController();
        $file_info = $pictureLiveUploadsFileObj->commonUpload($this->request);
        if ($file_info['code'] != 200) {
            return $this->returnApi(201, $file_info['msg']);
        }
        $user_id = $this->request->user_info['id'];
        $data['serial_number'] = $this->model->getSerialNumber('P');
        $data['user_id'] = $user_id;
        $data['act_id'] = $this->request->act_id;
        $data['cover'] = $file_info['content']['cover'];
        $data['img'] = $file_info['content']['img'];
        $data['thumb_img'] = $file_info['content']['thumb_img'];
        $data['width'] = $file_info['content']['width'];
        $data['height'] = $file_info['content']['height'];
        $data['size'] = $file_info['content']['size'];
        $data['ratio'] = $file_info['content']['ratio'];
        $data['way'] = 1;
        $data['status'] = $act_info['is_check'] == 2 ? 1 : 3;
        DB::beginTransaction();
        try {
            $this->model->add($data);

            /*消息推送*/
            // $system_id = $this->systemAdd('线上大赛投稿作品', $user_id, $account_id, 3, intval($this->model->id), '线上大赛：【' . $contestInfo->title . '】投稿成功，等待后台管理员审核！');

            $msg = $act_info['is_check'] == 2 ? '上传成功!' : '上传成功，等待后台管理员审核!';

            DB::commit();
            return $this->returnApi(200, $msg, true); //返回用户已投稿数量
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 添加图片浏览量
     * @param token 用户token
     * @param works_id 作品id
     */
    public function addBrowseNumber()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_add_browse_number')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //更新浏览量
        $this->model->updateBrowseNumber($this->request->works_id, 5, 30);
        return $this->returnApi(200, "添加成功", true);
    }
}
